package activator;

import library.service.Book;
import library.service.LibraryService;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;

public class Activator implements BundleActivator {

	private static final String BOOK_NAME_OLD = "Cooking";
	private static final String BOOK_NAME_NEW = "OSGi";
	ServiceReference libServiceRef;
	ServiceReference libServiceRef2;
	LibraryService libService;
	LibraryService libService2;
	BundleContext bundleContext;

	public void start(BundleContext context) throws Exception {
		this.bundleContext = context;
		libServiceRef = context.getServiceReference(LibraryService.class
				.getName());

		// System.out.println("----- CONSUMER-2: Search # 1 -----");
		// findBook(BOOK_NAME_NEW);

		// if(libService!=null){
		// System.out.println("CONSUMER-2: ungetService() method called.");
		// bundleContext.ungetService(libServiceRef);
		// }

		libService = (LibraryService) bundleContext.getService(libServiceRef);
		System.out.println("libServiceRef: " + libServiceRef);
		System.out.println("libService: " + libService);

		System.out.println("---- Part 2 -----");
		libServiceRef2 = context.getServiceReference(LibraryService.class
				.getName());
		libService2 = (LibraryService) bundleContext.getService(libServiceRef2);
		System.out.println("libServiceRef2: " + libServiceRef2);
		System.out.println("libService2: " + libService2);

		bundleContext.ungetService(libServiceRef2);
		libServiceRef2 = null;
		libService2 = null;

		// System.out.println("----- CONSUMER-2: Search # 2");
		// findBook(BOOK_NAME_OLD);
	}

	private void findBook(String bookName) {
		if (libServiceRef != null) {
			System.out.println("CONSUMER-2: getService() method called.");
			libService = (LibraryService) bundleContext
					.getService(libServiceRef);

			if (libService != null) {
				Book foundBook = libService.findBookByName(bookName);
				if (foundBook != null) {
					System.out.println("CONSUMER-2: Book FOUND: \"" + bookName
							+ "\"");
				} else {
					System.out.println("CONSUMER-2: Book NOT FOUND: \""
							+ bookName + "\"");
				}
			}
		}

	}

	public void stop(BundleContext context) throws Exception {

		// libService 1 clean up
		if (libService != null) {
			System.out.println("CONSUMER-2: ungetService() method called"
					+ " for libService #1");
			bundleContext.ungetService(libServiceRef);
			libService = null;
			libServiceRef = null;
			System.out.println("CONSUMER-2: stop() method finish.");
		}

		// libService 2 clean up
		if (libService2 != null) {
			System.out.println("CONSUMER-2: ungetService() method called "
					+ " for libService #2");
			bundleContext.ungetService(libServiceRef2);
			libService2 = null;
			libServiceRef2 = null;
			System.out.println("CONSUMER-2: stop() method finish.");
		}

		bundleContext = null;
	}

}
